<?php


namespace App\Service\Command\Admin;


use App\Http\Response\JsonResult;
use App\Http\Response\ResponseCode;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class LoginCommandService
{

    /**
     * 登录逻辑
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function login($params):JsonResponse
    {
        $flag = false;
        if ( Auth::guard('admin')->attempt(['username'=>$params['username'],'password'=>$params['password']]) ) {
            $flag = true;
        } else if ( Auth::guard('admin')->attempt(['mobile'=>$params['username'],'password'=>$params['password']]) ) {
            $flag = true;
        } else if ( Auth::guard('admin')->attempt(['email'=>$params['username'],'password'=>$params['password']]) ) {
            $flag = true;
        }


        if ( $flag ) {

            $user = Auth::guard('admin')->user();
            $user->last_login_ip =  request()->getClientIp();
            $user->last_login_time =  Carbon::now()->toDateTimeString();
            $user->save();
            Auth::guard('admin')->setUser($user);

            $roles = $user->roles()->get(['auth','role_id'])->toArray();

            $auth = [];
            $roleIds = [];
            foreach ($roles as $role) {
                $temp = json_decode($role['auth'],true);
                $auth = array_merge($auth,$temp);
                $roleIds[] = $role['role_id'];
            }

            session([ 'admin' => $this->setSessionUser($user),'auth' => array_unique($auth),'roleIds'=> $roleIds]);

            return JsonResult::returnJson(ResponseCode::SUCCESS);
        } else {
            return JsonResult::returnJson(ResponseCode::USER_EXIST_OR_FAIL_PASS);
        }
    }

    protected function setSessionUser($user)
    {
        $userArry = [
            'id' => $user->id,
            'nick' => $user->nick,
            'mobile' => $user->mobile,
            'email' => $user->email,
            'role_id' => $user->role_id,
        ];

        return $userArry;
    }


}